/**
 * 向后端请求用户的菜单，动态生成路由
 */
import { constantRouterMap } from '@/config/router.config'
import { generatorDynamicRouter } from '@/router/generator-routers'

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: [],
    permissions: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    }
  },
  actions: {
    GenerateRoutes ({ commit }, routers) {
      return new Promise(resolve => {
        const permissions = []
        for (let i = 0; i < routers.length; i++) {
            if (routers[i].menuType === 3) {
              permissions.push(routers[i].url)
              routers.splice(i, 1)
              i--
            }
        }
        commit('SET_PERMISSIONS', permissions)
        generatorDynamicRouter(routers).then(routers => {
          commit('SET_ROUTERS', routers)
          resolve()
        })
      })
    }
  }
}

export default permission
